package com.InterestingExercises;

import java.util.Scanner;

public class 输入整数合法性判断 {
    public static void main(String[] args) {
        int temp;
        while (true) {
            temp = getInt();
            System.out.println("temp = " + temp);
        }
    }


    public static int getInt() {
        Scanner sc = new Scanner(System.in);
        String temp;
        int len = 1;

        // 进行合法性判断,不合法则一直输入
        boolean flag = true;
        while (flag) {
            try {
                System.out.print("请输入一个4-20之间的整数:");
                temp = sc.next();
                len = Integer.parseInt(temp);
                while (len < 4 || len > 20) {
                    System.out.print("输入不合法,不在允许范围内!\n请输入一个4-20之间的整数:");
                    temp = sc.next();
                    len = Integer.parseInt(temp);
                }
                System.out.println("输入成功~");
                flag = false;
            } catch (NumberFormatException e) {
                System.out.println("输入不合法,不能输入非数字字符!");
            }
        }
        return len;
    }


}

